package cn.demomaster.quickpicturer.activity;

import static cn.demomaster.quickpicturer.helper.PhotoHelper.PHOTOHELPER_RESULT_PATH;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.demomaster.quickcompat.util.QDFileUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.demomaster.quickpicturer.R;
import cn.demomaster.quickpicturer.view.CameraCropView;
import cn.demomaster.quickpicturer.view.CustomCameraPreview;


/**
 * Created by Squirrel桓
 * 读取身份证界面
 */
public class CameraIDCardActivity extends BaseActivity {

    private ImageView iv_back;
    private static final String TAG = "CameraIDCardActivity";
    /**
     * 身份证正面
     */
    public final static int TYPE_ID_CARD_FRONT = 1;
    /**
     * 身份证反面
     */
    public final static int TYPE_ID_CARD_BACK = 2;

    private CustomCameraPreview customCameraPreview;
    private CameraCropView camera_crop_view;
    private ImageView btn_take_photo;
//
//    private OptionsMenu optionsMenu;
//    private OptionsMenu.Builder optionsMenubuilder;
//
//    //获取自定义菜单
//    public OptionsMenu.Builder getOptionsMenuBuilder() {
//        if (optionsMenubuilder == null) {
//            optionsMenubuilder = new OptionsMenu.Builder(mContext);
//        }
//        return optionsMenubuilder;
//    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        int type = getIntent().getIntExtra("type", 0);

        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //ORIENTATION_PORTRAIT
        setContentView(R.layout.activity_camera_idcard);
        // 针对非AppCompat活动
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        //getActionBarTool().setStateBarColorAuto(true);
        setTitle("身份证拍照");
//        getActionBarTool().setRightOnClickListener(v -> optionsMenu.show());
//        getActionBarTool().getRightView().setImageResource(R.drawable.ic_more_vert_black_24dp);
//        // 获取底部导航栏高度
//        Resources resources = getResources();
//        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
//        int navigationBarHeight = resources.getDimensionPixelSize(resourceId);
//
//        // 设置底部内边距
//        View bottomLayout = findViewById(android.R.id.content);
//        bottomLayout.setPadding(0, 0, 0, navigationBarHeight);

        customCameraPreview = findViewById(R.id.camera_surface);
        camera_crop_view = findViewById(R.id.camera_crop_view);

        //获取屏幕最小边，设置为cameraPreview较窄的一边
        float screenMinSize = Math.min(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
        //根据screenMinSize，计算出cameraPreview的较宽的一边，长宽比为标准的16:9
        //float maxSize = screenMinSize / 9.0f * 16.0f;

        /*cropView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                cropView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                LinearLayout.LayoutParams cropParams  = (LinearLayout.LayoutParams) cropView.getLayoutParams();
                float width =cropView.getWidth();
                float height = (int) (width * 9/16 );
                cropParams.height = (int)height;
                cropView.setLayoutParams(cropParams);
            }
        });*/

        switch (type) {
            case TYPE_ID_CARD_FRONT:
                camera_crop_view.setTip("请将身份证（正面）放在方框内");
                break;
            case TYPE_ID_CARD_BACK:
                camera_crop_view.setTip("请将身份证（反面）放在方框内");
                break;
        }

        customCameraPreview.setOnClickListener(v -> customCameraPreview.focus());
        btn_take_photo = findViewById(R.id.camera_take);
        btn_take_photo.setOnClickListener(v -> takePhoto());
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /*@Override
    public int getMenuRes() {
        return R.menu.menu_camera_idcard_action;
    }

    @Override
    public void initOptionsMenu(Menu menu) {
        List<NavMenuItem> menus = new ArrayList<>();
        for (int i = 0; i < menu.size(); i++) {
            NavMenuItem menu1 = new NavMenuItem(menu.getItem(i));
            menu1.setTitle("从相册中选取");
            menus.add(menu1);
        }
        if (optionsMenubuilder == null) {
            optionsMenubuilder = getOptionsMenuBuilder().setMenus(menus)
                    .setAlpha(.6f)
                    .setBackgroundRadius(20)
                    .setWithArrow(true)
                    .setArrowHeight(30)
                    .setArrowWidth(30)
                    .setGravity(QuickGravity.BOTTOM)
                    .setDividerColor(getResources().getColor(R.color.transparent))
                    .setAnchor(getActionBarTool().getRightView());
        }

        if (optionsMenu == null) {
            optionsMenu = new OptionsMenu(optionsMenubuilder);
        }
        optionsMenu.setMenus(menus);
        optionsMenu.setAnchor(getActionBarTool().getRightView());
        optionsMenu.setOnMenuItemClicked(new OptionsMenu.OnMenuItemClicked() {
            @Override
            public void onItemClick(NavMenuItem menu, int position, View view) {
                onOptionsItemSelected(menu.getMenuItem());
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.action_select_from_gallery){
            optionsMenu.dismiss();
            //选取图片并截取
            *//*photoHelper.selectPhotoFromGalleryAndCrop(new PhotoHelper.OnTakePhotoResult(){
                @Override
                public void onSuccess(Intent data, String path) {
                    setImageToView(data);
                }

                @Override
                public void onFailure(String error) {

                }
            });*//*
            //只选取图片不截取
            getPhotoHelper().selectPhotoFromGallery(new PhotoHelper.OnTakePhotoResult() {
                @Override
                public void onSuccess(Intent data, String path) {
                    String relPath = QDFileUtil.getRealPathFromURI(mContext, data.getData());
                    //setImageToView(data);
                    //拍照完成，返回对应图片路径
                    Intent intent = new Intent();
                    intent.putExtra(PHOTOHELPER_RESULT_PATH, relPath);
                    setResult(RESULT_OK, intent);
                    finish();
                }

                @Override
                public void onFailure(String error) {

                }
            });
        }
        return super.onOptionsItemSelected(item);
    }*/

    private void takePhoto() {
        btn_take_photo.setVisibility(View.GONE);
        customCameraPreview.setEnabled(false);
        customCameraPreview.takePhoto((data, camera) -> {
            //子线程处理图片，防止ANR
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = null;
                    if (data != null) {
                        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                        camera.stopPreview();
                    }
                    if (bitmap != null) {
                        //计算裁剪位置
                        float left = camera_crop_view.getPercentage_Left();
                        float top = camera_crop_view.getPercentage_top();
                        float width = camera_crop_view.getPercentage_width();
                        float height = camera_crop_view.getPercentage_height();

                        //裁剪及保存到文件
                        Bitmap resBitmap = Bitmap.createBitmap(bitmap,
                                (int) (left * bitmap.getWidth()),
                                (int) (top * bitmap.getHeight()),
                                (int) (width * bitmap.getWidth()),
                                (int) (height * bitmap.getHeight()));

                        String path = "";
                        //String path = QDFileUtil.saveBitmap(mContext,resBitmap);
                        // 在应用私有目录下创建文件
                        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                        String imageFileName = "JPEG_" + timeStamp + "_";
                        try {
                            File image = File.createTempFile(
                                    imageFileName,  /* prefix */
                                    ".jpg",         /* suffix */
                                    storageDir      /* directory */
                            );
                            path = image.getAbsolutePath();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        if (!bitmap.isRecycled()) {
                            bitmap.recycle();
                        }
                        if (!resBitmap.isRecycled()) {
                            resBitmap.recycle();
                        }
                        //拍照完成，返回对应图片路径
                        Intent intent = new Intent();
                        intent.putExtra(PHOTOHELPER_RESULT_PATH, path);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                }
            }).start();
        });
    }

    private static final int GALLERY_Photo_REQUEST_CODE = 300;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int CROP_SMALL_PICTURE = 5;
    private Uri fileUri;

    //获取返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: requestCode: " + requestCode + ", resultCode: " + requestCode + ", data: " + data + ",resultCode:" + resultCode);
        switch (requestCode) {
            //如果是拍照
            case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
                Log.d(TAG, "CAPTURE_IMAGE");
                if (RESULT_OK == resultCode) {
                    Log.d(TAG, "RESULT_OK");
                    // Check if the result includes a thumbnail Bitmap
                    if (data != null) {
                        // 没有指定特定存储路径的时候
                        Log.d(TAG, "data is NOT null, file on default position.");
                        // 指定了存储路径的时候（intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);）
                        // Image captured and saved to fileUri specified in the Intent
                        if (data.hasExtra("data")) {
//                            startPhotoZoom(data.getData());
                            setImageToView(data);
                            //Bitmap thumbnail = data.getParcelableExtra("data");
                        }
                    } else {
                        //startPhotoZoom(fileUri);
                    }
                }
                break;
            //从相册选取
            case GALLERY_Photo_REQUEST_CODE:
                Log.d(TAG, "GALLERY");
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        //startPhotoZoom(data.getData());
                    }
                }
                break;
            case CROP_SMALL_PICTURE:
                if (data != null) {
                    // setImageToView(data);
                }
            default:
                break;
        }
    }

    protected void setImageToView(final Intent data) {
        //showProgress("正在处理图片...", false);
        Bundle extras = data.getExtras();
        if (extras != null) {
            final Bitmap bitmap = extras.getParcelable("data");
            //photo = ImageUtils.toRoundBitmap(photo, fileUri); // ���ʱ���ͼƬ�Ѿ��������Բ�ε���
            //photo = ImageUtils.savePhoto(photo, Constants.APP_PATH_PICTURE, "")
            new Thread(() -> {
                if (bitmap != null) {
                    String path = QDFileUtil.saveBitmap(mContext,bitmap);
                    if (!bitmap.isRecycled()) {
                        bitmap.recycle();
                    }
                    //拍照完成，返回对应图片路径
                    Intent intent = new Intent();
                    intent.putExtra(PHOTOHELPER_RESULT_PATH, path);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }).start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}